package hbase;

import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;
import org.apache.hadoop.hbase.coprocessor.ObserverContext;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
import org.apache.hadoop.hbase.regionserver.wal.WALEdit;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class MyProcessor extends BaseRegionObserver {
    @Override
    public void prePut(ObserverContext<RegionCoprocessorEnvironment> e, Put put, WALEdit edit, Durability durability) throws IOException {
        Table table = e.getEnvironment().getTable(TableName.valueOf("relations"));
        Map.Entry<byte[], List<Cell>> entry = put.getFamilyCellMap().firstEntry();
        Put p = new Put(CellUtil.cloneValue(entry.getValue().get(0)));
        p.addColumn(CellUtil.cloneFamily(entry.getValue().get(0)), put.getRow(), put.getRow());
        table.put(p);
    }

    @Override
    public void preDelete(ObserverContext<RegionCoprocessorEnvironment> e, Delete delete, WALEdit edit, Durability durability) throws IOException {
        Table table = e.getEnvironment().getTable(TableName.valueOf("relations"));
        Cell cell = delete.getFamilyCellMap().firstEntry().getValue().get(0);
        Delete d = new Delete(CellUtil.cloneQualifier(cell));
        d.addColumn(CellUtil.cloneFamily(cell), delete.getRow());
        table.delete(d);
    }
}
